﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting;
using FrienDev.Api;
using FrienDev.Data;

namespace FrienDev.BusinessRules
{
    public class TrackRules
    {
        public static TrackRules Instance = new TrackRules();

        private FrienDevDataContext m_DataContext = FrienDevDataContext.Instance;

        private TrackRules()
        {
        }

        public object GetTrackByUserId(string userId, int count)
        {
            User user = UserRules.Instance.GetUserByUserId(userId);
            var tracks = from t in m_DataContext.Tracks
                         where t.UserApplication.UserId == userId
                         orderby t.TrackDateTime descending
                         select new
                         {
                             fullname = user.FullName,
                             userId = user.UserId,
                             text = GetTrackText(t),
                             time = t.TrackDateTime
                         };
            return tracks.Take(count);
        }

        public object GetFriendsTrackByUserId(string userId, int count)
        {
            var tracks = from f in m_DataContext.Friends
                         join ua in m_DataContext.UserApplications
                            on f.FriendId equals ua.UserId
                         from t in ua.Tracks
                         where f.UserId == userId && f.IsAccepted == true
                         orderby t.TrackDateTime descending
                         select new
                         {
                             fullname = f.FriendUser.FullName,
                             userId = f.FriendId,
                             text = GetTrackText(t),
                             time = t.TrackDateTime
                         };
            return tracks.Take(count);
        }

        private string GetTrackText(Track track)
        {
            FrienDevApplication application = FrienDevAppPool.Instance.GetApplication(
                track.UserApplication.Application.AssemblyName,
                track.UserApplication.Application.ClassName);
            if (application != null)
            {
                string[] parameters = track.TrackContent.Split(new string[] { "#####" }, StringSplitOptions.None);
                return application.GetTrackText(track.TrackType, parameters);
            }
            return "";
        }
    }
}
